import {
  TableColumnProps, Table, Row, Col, Space, Dropdown, Menu,
  Button, DropdownButton
} from 'ant-design-vue'
import { DownOutlined, CheckOutlined } from '@ant-design/icons-vue'
import {
  PropType, computed, defineComponent, ref, onMounted, toRefs, Teleport, cloneVNode
} from 'vue'

//
// ['export', { key: 'export', label: '新增' }]
const opraMap = new Map([
  ['add', { key: 'add', label: '新增' }],
  ['reload', { key: 'reload', label: '刷新' }],
  ['pure', { key: 'pure', label: '新增' }]
])

Array.from(opraMap, ([key, value]) => ({ ...value }))

/**
 * @description Table Pro 超级table 将各种业务与操作融合起来
 *
 */
const TablePro = defineComponent({
  props: {
    columns: {
      type: Array as PropType<TableColumnProps[]>,
      require: true
    },
    service: {
      type: Function,
      default: () => {}
    },
    serviceParams: {
      type: Object,
      default: () => {}
    },
    easy: {
      type: Boolean,
      default: true
    },
    pagination: {
      type: Object as PropType<{pageSize: number} | boolean>,
      default: () => ({ pageSize: 10 })
    },
    hiddenMeunKeys: {
      type: Array as PropType<string[]>,
      default: () => []
    }
  },
  emits: ['add'],
  setup (props, ctx) {
    const { columns, service, pagination, serviceParams, hiddenMeunKeys } = toRefs(props)

    const loading = ref<boolean>(false)

    const columnsProPlanVisible = ref<boolean>(false)

    const columnsPro = ref(columns.value!.map(item => ({ ...item, _active: true })))

    const pageSize = computed(() => typeof pagination.value === 'boolean' ? 10 : pagination.value.pageSize)

    const paginationRef = ref({
      current: 1,
      pageSize: pageSize.value,
      total: 0
    })

    const dataSource = ref([])

    const reload = (params?: {page: number}) => {
      if (params?.page) {
        paginationRef.value.current = params.page
      }
      dispatchRequest()
    }
    const dispatchRequest = async () => {
      loading.value = true
      const { data, sum } = await service.value({
        ...serviceParams.value,
        page: paginationRef.value.current,
        pageSize: paginationRef.value.pageSize
      })
      loading.value = false
      paginationRef.value.total = sum
      dataSource.value = data
    }

    const onChangePage = (page: number, pageSize: number) => {
      paginationRef.value.current = page
      paginationRef.value.pageSize = pageSize
      reload()
    }

    const pureVisible = ref(true)

    onMounted(() => {
      service && dispatchRequest()
    })

    // 放大图表
    const pure = () => {
      pureVisible.value = false

      const pureNode = document.getElementById('teleport-full-container')
      pureNode!.style.zIndex = '1000'
      const close = () => {
        pureVisible.value = true
        pureNode!.style.zIndex = '-1'
        pureNode?.removeEventListener('click', close)
      }
      pureNode?.addEventListener('click', close)
    }

    const opraMeun = (
      <Menu>
        {/* {
          Array.from(opraMap, ([key, value]) => ({...value})).map( item => Menu.Item key={1} onClick={() => pure()} > 放大 </Menu.Item> )
        } */}
        { hiddenMeunKeys.value.includes('add') ? null : <Menu.Item key={0} onClick={() => ctx.emit('add')} > 新增 </Menu.Item> }
        <Menu.Item key={1} onClick={() => pure()} > 放大 </Menu.Item>
      </Menu>
    )

    ctx.expose({ reload })

    return () => (

        <Row style={{ width: '100%' }} >
          <Col span={24} >
            <Row style={{ width: '100%' }} >
              <Col span={12} >
                {ctx.slots.search?.()}
              </Col>
              <Col span={12} style={{ display: 'flex', justifyContent: 'end' }} >
                <Space>
                <DropdownButton
                    onUpdate:open={ () => columnsProPlanVisible.value = !columnsProPlanVisible.value }
                    open={ columnsProPlanVisible.value}
                    overlay={
                      <Menu
                      >
                        {
                          columnsPro.value.map(column =>
                          <Menu.Item key={column.key} onClick={ () => column._active = !column._active } >
                            <Row gutter={[8, 8]} justify='space-between' >
                              <Col>{column.title}</Col>
                              <Col>{column._active ? <CheckOutlined /> : null}</Col>
                            </Row>
                          </Menu.Item>
                          )
                        }
                      </Menu>
                    }
                  >
                  筛选
                </DropdownButton>
                <DropdownButton
                    trigger={['click', 'hover']}
                    overlay={ hiddenMeunKeys.value.length !== 2 ? opraMeun : null}
                  >
                    <div onClick={() => reload()} >刷新 </div>
                </DropdownButton>
                </Space>
              </Col>
            </Row>
          </Col>
          <Col span={24} >

            <Teleport disabled={pureVisible.value} to="#teleport-full-container" >
              <Table
                style={{ marginTop: '20px', width: pureVisible.value ? '100%' : '100vw', cursor: pureVisible.value ? 'normal' : 'not-allowed' }}
                columns={columnsPro.value.filter(item => item._active)}
                loading={loading.value}
                pagination={ typeof pagination === 'boolean' ? pagination : { ...paginationRef.value, onChange: onChangePage }}
                dataSource={columnsPro.value.filter(item => item._active).length ? dataSource.value : []}
                v-slots={{
                  bodyCell (scope) {
                    return ctx.slots.render?.({ column: scope.column, record: scope.record })
                  }
                }}
              >
              </Table>
             </Teleport>
          </Col>
        </Row>

    )
  }
})

export default TablePro
